<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批量编辑记忆内容</title>
    <link rel="stylesheet" href="css/style.css">
    <!-- Quill.js 富文本编辑器 -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
</head>
<body>
    <div class="batch-edit-page">
        <div class="header">
            <button class="back-btn" onclick="goBack()">返回</button>
            <div class="page-title" id="pageTitle">批量编辑第1组</div>
        </div>

        <div class="batch-edit-container">
            <div class="memories-grid" id="memoriesGrid">
                <!-- 记忆内容编辑表单将在这里动态生成 -->
            </div>
            
            <div class="batch-actions">
                <button class="add-new-btn" onclick="addNewMemory()">添加</button>
                <button class="save-btn" onclick="saveAllMemories()">保存所有</button>
                <button class="cancel-btn" onclick="goBack()">取消</button>
            </div>
        </div>
    </div>

    <script src="js/utils.js"></script>
    <script src="js/db.js"></script>
    <script src="js/app.js"></script>
    <script>
        let currentGroupId = null;
        let currentGroup = null;
        let currentDay = 1; // 计算得到的当前天数，用于首次填写的条目归入今日
        let memories = [];
        let contentEditors = new Map(); // 存储每个记忆内容的富文本编辑器实例

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', async function() {
            await initDatabase();
            
            // 从URL参数获取组ID
            const urlParams = new URLSearchParams(window.location.search);
            currentGroupId = parseInt(urlParams.get('groupId'));
            
            if (!currentGroupId) {
                alert('无效的组ID');
                goBack();
                return;
            }

            // 加载组信息
            currentGroup = await db.getGroup(currentGroupId);
            if (!currentGroup) {
                alert('组不存在');
                goBack();
                return;
            }

            document.getElementById('pageTitle').textContent = `批量编辑${currentGroup.name}`;
            // 计算当前天数（基于记忆开始时间和今天）
            currentDay = calculateCurrentDay(currentGroup.memoryStartTime || currentGroup.createTime);
            
            loadMemories();
        });

        // 计算当前天数（与每日页保持一致）
        function calculateCurrentDay(createTime) {
            const createDate = new Date(createTime);
            const today = new Date();
            createDate.setHours(0, 0, 0, 0);
            today.setHours(0, 0, 0, 0);
            const diffTime = today - createDate;
            const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1;
            return Math.max(1, Math.min(diffDays, 100));
        }

        // 判断富文本内容是否为空（忽略占位符和空标签）
        function isContentEmpty(html) {
            if (!html) return true;
            const cleaned = html
                .replace(/<p><br><\/p>/gi, '')
                .replace(/\s+/g, '')
                .replace(/<[^>]*>/g, '');
            return cleaned.length === 0;
        }

        // 格式化时间显示
        function formatTime(createTime) {
            const date = new Date(createTime);
            const now = new Date();
            const diffMs = now - date;
            const diffMinutes = Math.floor(diffMs / (1000 * 60));
            const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
            const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

            if (diffMinutes < 1) {
                return '刚刚';
            } else if (diffMinutes < 60) {
                return `${diffMinutes}分钟前`;
            } else if (diffHours < 24) {
                return `${diffHours}小时前`;
            } else if (diffDays < 7) {
                return `${diffDays}天前`;
            } else {
                return date.toLocaleDateString('zh-CN', {
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }
        }

        // 加载记忆内容
        async function loadMemories() {
            memories = await db.getMemoriesByGroup(currentGroupId);
            const container = document.getElementById('memoriesGrid');
            
            container.innerHTML = memories.map((memory, index) => {
                // 转义HTML特殊字符，防止破坏HTML属性
                const escapedHint = (memory.hint || '').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                return `
                <div class="memory-edit-item">
                    <div class="memory-number">${index + 1}</div>
                    <div class="memory-inputs">
                        <input type="text" 
                               class="hint-input" 
                               placeholder="输入记忆提示" 
                               value="${escapedHint}"
                               data-memory-id="${memory.id}"
                               data-field="hint">
                        <div class="rich-text-container">
                            <div class="rich-text-editor" id="contentEditor_${memory.id}"></div>
                        </div>
                    </div>
                    <div class="memory-time">
                        ${formatTime(memory.createTime)}
                    </div>
                    <div class="memory-actions">
                        <button class="delete-btn" onclick="deleteMemory(${memory.id})" title="删除此条目">×</button>
                    </div>
                </div>
            `;
            }).join('');
            
            // 初始化富文本编辑器
            initContentEditors();
        }

        // 初始化富文本编辑器
        function initContentEditors() {
            const toolbarOptions = [
                [{ 'header': [1, 2, 3, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'indent': '-1'}, { 'indent': '+1' }],
                ['link', 'image'],
                ['clean']
            ];

            memories.forEach(memory => {
                const editorId = `contentEditor_${memory.id}`;
                const editorElement = document.getElementById(editorId);
                
                if (editorElement) {
                    const editor = new Quill(editorElement, {
                        theme: 'snow',
                        placeholder: '输入你要记忆的完整内容...',
                        modules: {
                            toolbar: toolbarOptions
                        }
                    });
                    
                    // 设置内容
                    if (memory.content) {
                        editor.root.innerHTML = memory.content;
                    }
                    
                    // 存储编辑器实例
                    contentEditors.set(memory.id, editor);
                }
            });
        }

        // 保存所有记忆内容
        async function saveAllMemories() {
            try {
                console.log('开始保存所有记忆内容...');
                
                const hintInputs = document.querySelectorAll('.hint-input');
                console.log('找到的提示输入框数量:', hintInputs.length);
                
                const updates = [];
                
                // 收集所有更新
                for (const hintInput of hintInputs) {
                    const memoryId = hintInput.dataset.memoryId;
                    const editor = contentEditors.get(parseInt(memoryId));
                    
                    console.log(`处理记忆内容 ${memoryId}:`, {
                        memoryId: memoryId,
                        hint: hintInput.value,
                        content: editor ? editor.root.innerHTML : ''
                    });
                    
                    if (memoryId && memoryId !== 'undefined' && memoryId !== 'null' && editor) {
                        const content = editor.root.innerHTML.trim();
                        const newHint = hintInput.value.trim();

                        // 根据当前内存列表，判断此条是否首次填写内容
                        const original = memories.find(m => m.id === parseInt(memoryId));
                        const wasEmptyBefore = original && (!original.hint || original.hint.trim() === '') && (!original.content || isContentEmpty(original.content));
                        const isNowFilled = (newHint.length > 0) || !isContentEmpty(content);

                        // 基础更新数据
                        const updateData = {
                            id: parseInt(memoryId),
                            hint: newHint,
                            content: content
                        };

                        // 如果是首次填写，将其归入今日：设定 day = currentDay，并更新创建时间
                        if (wasEmptyBefore && isNowFilled) {
                            updateData.day = currentDay;
                            updateData.createTime = new Date().toISOString();
                        }

                        updates.push(updateData);
                    } else {
                        console.warn(`跳过无效的memoryId或编辑器: ${memoryId}`);
                    }
                }

                console.log('准备保存的更新:', updates);

                if (updates.length === 0) {
                    showMessage('没有需要保存的内容', 'warning');
                    return;
                }

                // 批量更新
                let successCount = 0;
                for (const update of updates) {
                    try {
                        console.log('正在更新记忆内容:', update);
                        const putData = {
                            hint: update.hint,
                            content: update.content
                        };
                        // 仅当需要时写入 day 与 createTime
                        if (typeof update.day === 'number') {
                            putData.day = update.day;
                        }
                        if (update.createTime) {
                            putData.createTime = update.createTime;
                        }
                        await db.updateMemory(update.id, putData);
                        console.log('更新完成:', update.id);
                        successCount++;
                    } catch (updateError) {
                        console.error(`更新记忆内容失败 (ID: ${update.id}):`, updateError);
                        // 继续处理其他更新
                    }
                }

                showMessage(`成功保存 ${successCount}/${updates.length} 条记忆内容！`, successCount > 0 ? 'success' : 'error');
                // 不自动返回，让用户继续编辑
                // goBack();
            } catch (error) {
                console.error('保存失败:', error);
                showMessage('保存失败: ' + error.message, 'error');
            }
        }

        // 显示消息
        function showMessage(message, type = 'info') {
            // 创建消息元素
            const messageEl = document.createElement('div');
            messageEl.className = `message message-${type}`;
            messageEl.textContent = message;
            messageEl.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 12px 20px;
                border-radius: 8px;
                color: white;
                font-weight: 500;
                z-index: 1000;
                animation: slideIn 0.3s ease;
                max-width: 300px;
            `;
            
            // 根据类型设置背景色
            if (type === 'success') {
                messageEl.style.backgroundColor = '#4CAF50';
            } else if (type === 'error') {
                messageEl.style.backgroundColor = '#f44336';
            } else if (type === 'warning') {
                messageEl.style.backgroundColor = '#ff9800';
            } else {
                messageEl.style.backgroundColor = '#2196F3';
            }
            
            document.body.appendChild(messageEl);
            
            // 3秒后自动移除
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 3000);
        }

        // 删除记忆条目
        async function deleteMemory(memoryId) {
            if (confirm('确定要删除这条记忆内容吗？此操作不可恢复！')) {
                try {
                    await db.deleteMemory(memoryId);
                    showMessage('记忆内容删除成功', 'success');
                    // 重新加载记忆列表
                    await loadMemories();
                } catch (error) {
                    console.error('删除记忆内容失败:', error);
                    showMessage('删除失败: ' + error.message, 'error');
                }
            }
        }

        // 添加新记忆条目
        async function addNewMemory() {
            try {
                // 重新获取当前记忆列表以获取最新的长度
                const currentMemories = await db.getMemoriesByGroup(currentGroupId);
                console.log('当前记忆列表:', currentMemories);
                
                // 找到最大的天数
                const maxDay = currentMemories.length > 0 ? Math.max(...currentMemories.map(m => m.day)) : 0;
                const nextDay = maxDay + 1;
                
                console.log('下一个天数:', nextDay);
                
                // 创建新的记忆条目
                const newMemoryId = await db.addMemory({
                    groupId: currentGroupId,
                    day: nextDay,
                    hint: '',
                    content: '',
                    reviewDays: [1, 2, 4, 7, 14, 21, 28, 50]
                });
                
                console.log('新创建的记忆ID:', newMemoryId);
                
                // 重新加载记忆列表
                await loadMemories();
                
                // 等待DOM更新
                setTimeout(() => {
                    // 滚动到新添加的条目
                    const newMemoryElement = document.querySelector(`[data-memory-id="${newMemoryId}"]`);
                    if (newMemoryElement) {
                        newMemoryElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        // 高亮新条目
                        newMemoryElement.style.backgroundColor = '#e8f4fd';
                        setTimeout(() => {
                            newMemoryElement.style.backgroundColor = '';
                        }, 2000);
                    } else {
                        console.error('找不到新添加的条目元素，ID:', newMemoryId);
                    }
                }, 200); // 增加等待时间以确保富文本编辑器初始化完成
                
                showMessage('新条目添加成功', 'success');
            } catch (error) {
                console.error('添加新条目失败:', error);
                showMessage('添加新条目失败: ' + error.message, 'error');
            }
        }

        // 返回上一页
        function goBack() {
            window.location.href = `daily.html?groupId=${currentGroupId}`;
        }
    </script>
</body>
</html>
